//
//  OrderEvaluationViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/29.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "OrderEvaluationViewController.h"
//#import "QBImagePicker/QBImagePickerController.h"
//#import "QBImagePicker.h"
#import "QBImagePickerController.h"
#import "AFNetworking.h"//主要用于网络请求方法
#import "UIKit+AFNetworking.h"//里面有异步加载图片的方法
#import "AFHTTPSessionManager.h"
#import "PlaceholderTextView.h"
#import "PublishTopicImageCell.h"
#import "MyAddTribeListViewController.h"
#import "ELCImagePickerController.h"

#import "GCQiniuUploadManager.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750
@interface OrderEvaluationViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, ELCImagePickerControllerDelegate, QBImagePickerControllerDelegate, UITextViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, PublishTopicDeleteDelegate, UIAlertViewDelegate>

@property (strong, nonatomic) PlaceholderTextView* contentTextView;
@property (strong, nonatomic) UILabel *tribename;
@property (strong, nonatomic) NSMutableArray *imgArray;
@property (strong, nonatomic) NSMutableArray *imgurlArray;
@property (strong, nonatomic) NSMutableArray *imgidArray;
@property (assign, nonatomic) CGFloat itemWidth;
@property (assign, nonatomic) NSInteger starNumer;

@property (strong, nonatomic) NSString *docid;

@end

@implementation OrderEvaluationViewController{
    UICollectionView *mcollectionView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    CGFloat goodsViewH = 200*kScale;
    UIView *goodsView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, goodsViewH)];
    [self.view addSubview:goodsView];
    CGFloat headerImageH = 164*kScale;
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 30*kScale, headerImageH, headerImageH);
    headerImage.backgroundColor = [UIColor cyanColor];
    [headerImage sd_setImageWithURL:[NSURL URLWithString:[_order.goods.headerImageUrl componentsSeparatedByString:@","][0]]];
    
    headerImage.layer.masksToBounds  = YES;
    [goodsView addSubview:headerImage];
//    CGFloat typeLableH = 41*kScale;
//    UILabel *typeLable = [[UILabel alloc]initWithFrame:CGRectMake(0 , 0, typeLableH, typeLableH)];
//    typeLable.textColor = [UIColor whiteColor];
//    typeLable.backgroundColor = ZallColorFromRGB(0x0fa2b6);;
//    typeLable.text = @"话";
//    
//    typeLable.textAlignment = NSTextAlignmentCenter;
//    [headerImage addSubview:typeLable];
    UILabel *introdocLable = [[UILabel alloc]init];
    introdocLable.font = [UIFont systemFontOfSize:14];
    introdocLable.numberOfLines = 2;
    //        introdocLable.lineBreakMode =  NSLineBreakByTruncatingTail;
    introdocLable.textColor = [UIColor colorWithRed:34/255.0 green:34/255.0 blue:34/255.0 alpha:1.0];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc]init];
    style.lineSpacing = 5;
    introdocLable.text = _order.goodsName;
    introdocLable.textColor = ZallColorFromRGB(0x444444);
    CGSize introSize = [introdocLable sizeThatFits:CGSizeMake(ScreenW-(headerImageH+3*30*kScale), MAXFLOAT)];
    
    //        NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:14], NSParagraphStyleAttributeName:style};
    //        introdocLable.attributedText = [[NSAttributedString alloc]initWithString:introdocLable.text attributes:attributes];
    
    introdocLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, ScreenW-(headerImageH+3*30*kScale), introSize.height);
    [goodsView addSubview:introdocLable];
    CGFloat starBtnH = 42*kScale;
    for (int i = 0; i < 5; i++)
    {
        UIButton *starBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [starBtn setBackgroundImage:[UIImage imageNamed:@"评价星级不带颜色"] forState:UIControlStateNormal];
        [starBtn setBackgroundImage:[UIImage imageNamed:@"评价星级带颜色"] forState:UIControlStateSelected];
        starBtn.frame = CGRectMake(headerImageH+2*30*kScale+(30*kScale+starBtnH)*i, headerImage.frame.origin.y+headerImageH-starBtnH, starBtnH, starBtnH);
//        starBtn.backgroundColor = [UIColor cyanColor];
        starBtn.tag = 20+i;
        [starBtn addTarget:self action:@selector(starBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [goodsView addSubview:starBtn];
        
    }
    self.view.backgroundColor = [UIColor whiteColor];
    self.contentTextView = [[PlaceholderTextView alloc]initWithFrame:CGRectMake(12, 10+goodsViewH+2*kScale, ScreenWidth-24, 114)];
    self.contentTextView.delegate = self;
    self.contentTextView.font = [UIFont systemFontOfSize:16.f];
    self.contentTextView.layer.borderWidth = 2.*kScale;
    self.contentTextView.layer.borderColor = ZallColorFromRGB(0x9e9e9e).CGColor;
    self.contentTextView.textColor = [UIColor blackColor];
    self.contentTextView.textAlignment = NSTextAlignmentLeft;
    self.contentTextView.editable = YES;
    self.contentTextView.placeholderColor = [UIColor lightGrayColor];
    self.contentTextView.placeholder = @"说点什么吧～";
    [self.view addSubview:self.contentTextView];
    
    //    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 12 + 114, ScreenWidth, 1)];
    //    line.backgroundColor = LineColor;
    //    [self.view addSubview:line];
    
    //照片Collection
    UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];
    //    flowlayout.minimumInteritemSpacing = 5;
    //    flowlayout.minimumLineSpacing = 5;
    //    flowlayout.itemSize = CGSizeMake((kScreenWidth-24-15)/4, 52);
    self.itemWidth = (ScreenWidth - 24 - 24 * 3) / 4;
    flowlayout.itemSize = CGSizeMake(self.itemWidth, self.itemWidth);
    // 设置最小行间距
    flowlayout.minimumLineSpacing = 19;
    // 设置垂直间距
    flowlayout.minimumInteritemSpacing = 24;
    
    mcollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(12, 114 + 12 + goodsViewH+5*kScale, ScreenWidth-24, self.itemWidth + 19) collectionViewLayout:flowlayout];
    [self.view addSubview:mcollectionView];
    mcollectionView.backgroundColor = [UIColor whiteColor];
//    mcollectionView.layer.borderWidth = 2*kScale;
//    mcollectionView.layer.borderColor = ZallColorFromRGB(0x9e9e9e).CGColor;
    [mcollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(12);
        make.right.equalTo(self.view.mas_right).offset(-12);
        make.height.mas_equalTo(self.itemWidth + 19);
        make.top.equalTo(self.contentTextView.mas_bottom).offset(12);
    }];
    [mcollectionView registerClass:[PublishTopicImageCell class] forCellWithReuseIdentifier:@"PublishTopicImageCell"];
    mcollectionView.delegate = self;
    mcollectionView.dataSource = self;
    [mcollectionView reloadData];

    
    [PublishData sharedPublishData].chooseTribeID = @"";
    [PublishData sharedPublishData].chooseTribeName = @"";
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [ViewFactory setNavigationBlack:self];
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"订单评论"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(goPop)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    UIButton *button = [ViewFactory makeNavigationTextButtonWhite:@"评论"];
    [button addTarget:self action:@selector(goPublish) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightButton;
    
    if ([PublishData sharedPublishData].chooseTribeName) {
        self.tribename.text = [PublishData sharedPublishData].chooseTribeName;
    }
}

- (void)goPop {
    [self.view endEditing:YES];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定要取消评论吗？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) { //确定
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (NSString*)DataTOjsonString:(id)object {
    NSString *jsonString = nil;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                       options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    return jsonString;
}

- (void)goPublish {
    [self.view endEditing:YES];
    if (self.contentTextView.text.length == 0) {
        [ViewFactory showInfoMsg:@"请输入评论内容！"];
        return;
    }
    if (!(_starNumer>0)) {
        [ViewFactory showInfoMsg:@"请进行星级评价"];
        return;
    }
    
    [ViewFactory showLoading];
    [self uploadImages];}

- (void)uploadImages {
    [self.imgurlArray removeAllObjects];
    [self.imgidArray removeAllObjects];
    NSMutableArray *dataarray = [NSMutableArray new];
    for (NSInteger i = 0; i < self.imgArray.count; i++) {
        UIImage *img = self.imgArray[i];
        NSData *imgdata = UIImageJPEGRepresentation(img, NORMALSIZE);
        [dataarray addObject:imgdata];
    }
    
    [[GCQiniuUploadManager sharedInstance] uploadDatas:dataarray progress:^(float percent) {
        
    } oneTaskCompletion:^(NSError *error, NSString *link, NSInteger index) {
        DYLog(@"upload index:%ld link:%@", index, link);
        if (link) {
            NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
            [self.imgurlArray addObject:resurl];
            [self.imgidArray addObject:link];
        }
    } allTasksCompletion:^{
        [self evaluationRequest];
    }];
}
- (void) evaluationRequest
{
    NSString *imgUrlStr = @"";
    for (int i = 0; i < self.imgurlArray.count; i++) {
        imgUrlStr = [NSString stringWithFormat:@",%@",self.imgurlArray[i]];
    }
    NSString *urlStr = [[NSString stringWithFormat:@"%@/product/AddContent?goods_id=%@&img_url=%@&order_id=%@&score=%ld&feedback=%@",APIYIGOU,_order.goodsId,imgUrlStr,_order.orderId,_starNumer,self.contentTextView.text]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        
        NSLog(@"77777%@",allDic);
        [ViewFactory showSuccess:@"评论成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(YTKBaseRequest *request) {
        [ViewFactory showInfoMsg:@"评论失败"];
    } failure:^(YTKBaseRequest *request) {
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];

}
//- (void)uploadDoc {
//    NSString *coverid = @"";
//    if (self.imgidArray.count > 0) {
//        coverid = self.imgidArray[0];
//    }
//    
//    NSMutableArray *parray = [[NSMutableArray alloc] init];
//    NSDictionary *pdict = @{
//                            @"sort_index": @0,
//                            @"md": self.contentTextView.text
//                            };
//    [parray addObject:pdict];
//    
//    NSMutableArray *picarray = [[NSMutableArray alloc] init];
//    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
//        NSString *imgid = self.imgidArray[i];
//        NSDictionary *picdict = @{
//                                  @"sort_index": [NSNumber numberWithInteger:i],
//                                  @"id": imgid,
//                                  @"media_type": @"00",
//                                  @"tag": @[
//                                          @{
//                                              @"sort_index": @1,
//                                              @"label_value": @"http://www.baidu.com",
//                                              @"txt_orient": @"0",
//                                              @"label_x": @"100",
//                                              @"label_y": @"100",
//                                              @"label_name": @"艺术1"
//                                              },
//                                          @{
//                                              @"sort_index": @2,
//                                              @"label_value": @"",
//                                              @"txt_orient": @"0",
//                                              @"label_x": @"200",
//                                              @"label_y": @"200",
//                                              @"label_name": @"艺术2"
//                                              }
//                                          ]
//                                  };
//        [picarray addObject:picdict];
//    }
//    
//    NSDictionary *qndict =
//    @{
//      @"title": self.contentTextView.text,
//      @"desc": self.contentTextView.text,
//      @"cover_img": @{
//              @"id": coverid,
//              @"media_type": @"00",
//              @"is_cover": @"00",
//              @"tag": @[
//                      @{
//                          @"sort_index": @1,
//                          @"label_value": @"http://www.baidu.com",
//                          @"txt_orient": @"0",
//                          @"label_x": @"100",
//                          @"label_y": @"100",
//                          @"label_name": @"艺术1"
//                          },
//                      @{
//                          @"sort_index": @2,
//                          @"label_value": @"",
//                          @"txt_orient": @"0",
//                          @"label_x": @"200",
//                          @"label_y": @"200",
//                          @"label_name": @"艺术2"
//                          }
//                      ]
//              },
//      @"content": @{
//              @"paragraph": parray,
//              @"img": picarray              }
//      };
//    
//    NSData *qndata =[qndict JSONData];
//    [[GCQiniuUploadManager sharedInstance] uploadData:qndata progress:^(float percent) {
//        DYLog(@"upload percent:%f", percent);
//    } completion:^(NSError *error, NSString *link, NSInteger index) {
//        if (link == nil) {
//            [ViewFactory showErrorStrMsg:@"上传失败！"];
//            return;
//        }
//        
//        DYLog(@"upload link:%@", link);
//        NSString *resurl = [NSString stringWithFormat:@"%@/%@", QNHOST, link];
//        self.docid = resurl;
//        [self publishTopic];
//    }];
//}
//
//- (void)publishTopic {
//    //content_type：00话题 01文章 is_cover:00封面图 01非封面图 media_type:00
//    NSString *coverurl = @"";
//    if (self.imgurlArray.count > 0) {
//        coverurl = self.imgurlArray[0];
//    }
//    NSMutableArray *picarray = [[NSMutableArray alloc] init];
//    for (NSInteger i = 0; i < self.imgidArray.count; i++) {
//        NSString *iscover = @"01";
//        if (i == 0) {
//            iscover = @"00";
//        }
//        NSString *imgid = self.imgidArray[i];
//        NSString *imgurl = self.imgurlArray[i];
//        NSDictionary *picdict = @{
//                                  @"is_cover": iscover,
//                                  @"media_id": imgid,
//                                  @"media_size": @0,
//                                  @"media_type": @"00",
//                                  @"media_url": imgurl,
//                                  @"sortindex": [NSNumber numberWithInteger:i],
//                                  @"tag": @[
//                                          @{
//                                              @"label_type": @"string",
//                                              @"label_value": @"string",
//                                              @"label_x": @"string",
//                                              @"label_y": @"string",
//                                              @"sortindex": @0,
//                                              @"txt_orient": @"string"
//                                              }
//                                          ]
//                                  };
//        [picarray addObject:picdict];
//    }
//    
//    NSString *tribeid = @"0";
//    if ([PublishData sharedPublishData].chooseTribeID.length > 0) {
//        tribeid = [PublishData sharedPublishData].chooseTribeID;
//    }
//    NSDictionary *textdict = @{
////                               @"content_id": @0,
////                               @"content_type": @"00",
////                               @"coverImg": coverurl,
////                               @"desc": self.contentTextView.text,
////                               @"doc_id": self.docid,
////                               @"media": picarray,
////                               @"title": self.contentTextView.text,
////                               @"tribe_id": tribeid,
////                               @"user_id": [UserData userid]
//                               @"order_id": _order.orderId,
//                               @"goods_id": _order.goodsId,
//                               @"img_url": picarray,
//                               @"feedback": self.contentTextView.text,
//                               
//                               };
//    
//    NSString *urlStr = [NSString stringWithFormat:@"%@/product/AddContent",APIYIGOU];
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [manager.requestSerializer setValue:[UserData usertoken] forHTTPHeaderField:@"Auth"];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    
//    
//    
//    [manager POST:urlStr parameters:textdict success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
//        if ([[dict valueForKey:@"code"] intValue] == 100) {
//            [ViewFactory showSuccess:@"评论成功！"];
//            [self.navigationController popViewControllerAnimated:YES];
//        } else {
//        }
//        DYLog(@"result:%@", dict.description);
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        NSLog(@"error %ld",(long)error.code);
//        [ViewFactory showErrorStrMsg:@"评论失败！"];
//    }];
//}

- (void)textViewDidChange:(UITextView *)textView {
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (self.imgArray.count + 1);
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    PublishTopicImageCell *cell = (PublishTopicImageCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"PublishTopicImageCell" forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.delegate = self;
    if (self.imgArray.count > 0) {
        if (indexPath.row == self.imgArray.count) {
            cell.deletebtn.hidden = YES;
            cell.icon.image = [UIImage imageNamed:@"post_Camera"];
        } else {
            cell.deletebtn.hidden = NO;
            UIImage *img = self.imgArray[indexPath.row];
            cell.icon.image = img;
        }
    } else {
        cell.deletebtn.hidden = YES;
        cell.icon.image = [UIImage imageNamed:@"post_Camera"];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self.view endEditing:YES];
    if (self.imgArray.count == 0) {
        [self clickAdd];
    } else {
        if (indexPath.row == self.imgArray.count) {
            [self clickAdd];
        }
    }
}

- (void)publishTopicDeleteOne:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.row;
    [self.imgArray removeObjectAtIndex:index];
    NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
    [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo((self.itemWidth + 19) * count);
    }];
    [mcollectionView reloadData];
}

- (void)clickAdd {
    [self.view endEditing:YES];
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction* takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openCamera];
    }];
    
    UIAlertAction* choosePictureAction = [UIAlertAction actionWithTitle:@"从手机相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self choosePhoto];
    }];
    
    [alertVC addAction:cancleAction];
    [alertVC addAction:takePhotoAction];
    [alertVC addAction:choosePictureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)openCamera {
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    
    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = sourceType;
    
    [self presentViewController:picker animated:YES completion:^{
    }];
}

- (void)choosePhoto {
    NSInteger maxCount = 10;
    if (ISIOS7 || ISIOS8_0) {
        ELCImagePickerController *elcPicker = [ELCImagePickerController new];
        elcPicker.maximumImagesCount = maxCount;
        elcPicker.imagePickerDelegate = self;
        [self presentViewController:elcPicker animated:YES completion:nil];
    } else {
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.assetCollectionSubtypes =@[
                                                         @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                         @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                         @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景图
                                                         @(PHAssetCollectionSubtypeSmartAlbumBursts), //连拍模式拍摄的照片
                                                         @(PHAssetCollectionSubtypeSmartAlbumFavorites)
                                                         ];
        imagePickerController.delegate = self;
        imagePickerController.allowsMultipleSelection = YES;
        imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        imagePickerController.maximumNumberOfSelection = maxCount;
        imagePickerController.showsNumberOfSelectedAssets = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.imgArray insertObject:image atIndex:0];
        NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
    }];
}

- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    //TODO:changeToData
    [picker dismissViewControllerAnimated:YES completion:^{
        for (int i = 0;i<[info count];i++) {
            UIImage *img = [[info objectAtIndex:i]objectForKey:@"UIImagePickerControllerOriginalImage"];
            [self.imgArray insertObject:img atIndex:0];
        }
        NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
        [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo((self.itemWidth + 19) * count);
        }];
        [mcollectionView reloadData];
    }];
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        DYLog(@"cancl");
    }];
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets {
    NSUInteger count = assets.count;
    __block NSUInteger select = 0;
    PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
    option.synchronous = YES;
    for (PHAsset *asset in assets) {
        [[PHCachingImageManager defaultManager]requestImageDataForAsset:asset options:option resultHandler:^(NSData * imageData, NSString * dataUTI, UIImageOrientation orientation, NSDictionary * info) {
            if(imageData) {
                [self.imgArray insertObject:[UIImage imageWithData:imageData] atIndex:0];
                select++;
            }
            if(select == count) {
                NSInteger count = (self.imgArray.count + 1) / 4 + ((self.imgArray.count + 1) % 4 > 0 ? 1 : 0);
                [mcollectionView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.height.mas_equalTo((self.itemWidth + 19) * count);
                }];
                [mcollectionView reloadData];
                [imagePickerController dismissViewControllerAnimated:YES completion:NULL];
                
                return;
            }
        }];
        
    }
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    [imagePickerController dismissViewControllerAnimated:NO completion:NULL];
}

//星级评价
- (void) starBtnClick:(UIButton*)sender
{
    for (int i = 0; i < 5; i++)
    {
         UIButton *starBtn = (UIButton *)[self.view viewWithTag:20+i];
        if (20+i>sender.tag) {
            starBtn.selected = NO;
        }
        else
        {
            starBtn.selected = YES;
        }
        _starNumer = sender.tag-19;
    }
    
}
ARRAY_INIT(imgArray)
ARRAY_INIT(imgurlArray)
ARRAY_INIT(imgidArray)
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
